package madixin.t121;

class Solution {
    //因为只能买卖一次，所以遍历找到最低价，并在该最低价之后找到最大差价
    public int maxProfit1(int[] prices) {
        if (prices == null || prices.length < 2) {
            return 0;
        }
        int lowPrice = Integer.MAX_VALUE;
        int maxProfit = 0;
        for (int price : prices) {
            if (price < lowPrice) {
                lowPrice = price;
            } else if (price - lowPrice > maxProfit) {
                maxProfit = price - lowPrice;
            }
        }
        return maxProfit;
    }

    //dp填表法，是利用状态转移方程和上一个状态来推导出现在的状态
    public int maxProfit(int[] prices) {
        if (prices == null || prices.length < 2) {
            return 0;
        }

        //0表示持有现金，1表示持有股票
        //i表示第几天
        int dp[][] = new int[prices.length][2];
        dp[0][0] = 0;
        dp[0][1] = -prices[0];
        for (int i = 1; i < prices.length; i++) {
            dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
            dp[i][1] = Math.max(dp[i - 1][1], -prices[i]);
        }

        return dp[prices.length - 1][0];
    }

    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(s.maxProfit(new int[]{7, 1, 5, 3, 6, 4}));
    }
}